<template>
  <div class="h5-customer-detail">
    <!-- 头部信息 -->
    <div class="header-section">
      <div class="customer-info">
        <div class="customer-name-row">
          <span
            class="customer-name"
            :class="{ 'ent-customer': CustomerValue.entId }"
            @click="wentEnt"
          >
            {{ CustomerValue?.name }}
          </span>
          <div class="nav-buttons">
            <el-button size="small" @click="emit('prev')" :disabled="isLoad" circle>
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <el-button size="small" @click="emit('next')" :disabled="isLoad" circle>
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 客户级别 -->
        <div class="info-row" v-if="CustomerValue.levelRespVO">
          <span class="label">客户级别:</span>
          <el-tag
            :style="{
              background: CustomerValue.levelRespVO.bgColor,
              color: CustomerValue.levelRespVO.textColor,
              border: 'none'
            }"
          >
            {{ CustomerValue.levelRespVO.name }}
          </el-tag>
        </div>

        <!-- 手机号 -->
        <div class="info-row" v-if="CustomerValue.mobile">
          <span class="label">手机:</span>
          <span class="phone-number" @click="onCall(CustomerValue, CustomerValue.mobile)">
            {{ CustomerValue.encryptMobile }}
            <el-icon><Phone /></el-icon>
          </span>
        </div>

        <!-- 负责人 -->
        <div class="info-row">
          <span class="label">负责人:</span>
          <span class="value">{{ CustomerValue.ownerUserName }}</span>
        </div>

        <!-- 创建人 -->
        <div class="info-row">
          <span class="label">创建人:</span>
          <span class="value">{{ CustomerValue.creatorName }}</span>
        </div>

        <!-- 所属模块 -->
        <div class="info-row" v-if="getModuleName(CustomerValue.moduleId)">
          <span class="label">所属模块:</span>
          <el-tag type="primary">{{ getModuleName(CustomerValue.moduleId).name }}</el-tag>
        </div>

        <!-- 标签 -->
        <div class="tags-section">
          <div class="tags-row">
            <el-tag
              v-for="tag in CustomerValue.labelList"
              :key="tag.id"
              :style="{
                background: tag.bgColor,
                color: tag.textColor,
                marginRight: '4px',
                marginBottom: '4px'
              }"
            >
              {{ tag.name }}
            </el-tag>
            <el-button size="small" @click="showTagPopup = true" class="edit-tag-btn" text>
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <div class="action-grid">
        <!-- 编辑 -->
        <div v-if="validateWrite" class="action-item" @click="openForm">
          <el-icon><Edit /></el-icon>
          <span>编辑</span>
        </div>

        <!-- 转移 -->
        <div v-if="validateOwnerUser" class="action-item" @click="transfer">
          <el-icon><Switch /></el-icon>
          <span>转移</span>
        </div>

        <!-- 更改成交状态 -->
        <div v-if="validateWrite" class="action-item" @click="handleUpdateDealStatus">
          <el-icon><Refresh /></el-icon>
          <span>成交状态</span>
        </div>

        <!-- 锁定/解锁 -->
        <div
          v-if="validateOwnerUser"
          class="action-item"
          @click="CustomerValue.lockStatus ? handleUnlock() : handleLock()"
        >
          <el-icon><Lock v-if="!CustomerValue.lockStatus" /><Unlock v-else /></el-icon>
          <span>{{ CustomerValue.lockStatus ? '解锁' : '锁定' }}</span>
        </div>

        <!-- 放入公海 -->
        <div v-if="validateOwnerUser" class="action-item" @click="handlePutPool">
          <el-icon><Grid /></el-icon>
          <span>放入公海</span>
        </div>

        <!-- 领取 -->
        <div v-if="isPool && !CustomerValue.ownerUserId" class="action-item" @click="handleReceive">
          <el-icon><Wallet /></el-icon>
          <span>领取</span>
        </div>

        <!-- 分配 -->
        <div
          v-if="isPool && !CustomerValue.ownerUserId"
          class="action-item"
          @click="handleDistributeForm"
        >
          <el-icon><User /></el-icon>
          <span>分配</span>
        </div>

        <!-- 删除 -->
        <div class="action-item" @click="delCustomer">
          <el-icon><Delete /></el-icon>
          <span>删除</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 标签编辑弹窗 -->
  <el-drawer v-model="showTagPopup" title="编辑标签" direction="btt" size="60%">
    <div class="tag-content">
      <div v-for="group in tagMap" :key="group.name" class="tag-group">
        <div class="group-name">{{ group.name }}</div>
        <div class="tag-list">
          <el-tag
            v-for="item in group?.labelList"
            :key="item.id"
            @click="changeTag(item.id)"
            :style="{
              background: tagValue.indexOf(item.id) != -1 ? item.bgColor : '#f4f4f5',
              color: tagValue.indexOf(item.id) != -1 ? item.textColor : '#909399',
              marginRight: '8px',
              marginBottom: '8px',
              cursor: 'pointer'
            }"
            class="tag-item"
          >
            {{ item.name }}
          </el-tag>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="submit" :loading="isLoading" style="width: 100%">
        确定
      </el-button>
    </template>
  </el-drawer>

  <!-- 表单组件 -->
  <CustomerFormH5 ref="formRef" @success="getCustomer" />
  <CrmTransferFormH5 ref="transferFormRef" @success="emit('closeDrawer')" />
  <CustomerDistributeFormH5 ref="distributeForm" @success="init" />
  <EnterpriseDetailsH5 ref="companyDetail" @refresh-val="init" />
</template>

<script setup>
import CustomerFormH5 from '@/views/crm/customer/CustomerForm.vue'
import CrmTransferFormH5 from '@/views/crm/permission/components/TransferForm.vue'
import * as CustomerApi from '@/api/crm/customer'
import * as customerTagApi from '@/api/crm/customerTagConfig/index'
import CustomerDistributeFormH5 from '@/views/crm/customer/pool/CustomerDistributeForm.vue'
import EnterpriseDetailsH5 from '@/views/ent/components/EnterpriseDetaill/index.vue'
import { useSoftPhoneStore } from '@/store/modules/softPhone'
import { usePhoneStore } from '@/store/modules/phone'
import { emitter } from '@/utils/eventBus.ts'
import {
  ArrowLeft,
  ArrowRight,
  Edit,
  Switch,
  Phone,
  Refresh,
  Lock,
  Unlock,
  Grid,
  Wallet,
  User,
  Delete
} from '@element-plus/icons-vue'

const useStore = usePhoneStore()
const useSoftPhone = useSoftPhoneStore()

const tagValue = ref([])
const showTagPopup = ref(false)
const isLoading = ref(false)

const props = defineProps({
  CustomerValue: Object,
  tagMap: Array,
  isLoad: Boolean,
  isPool: Boolean,
  validateWrite: Boolean,
  validateOwnerUser: Boolean,
  moduleOption: Array
})

watch(
  () => props.CustomerValue,
  (val) => {
    if (val && val.labelList) {
      tagValue.value = val.labelList.map((item) => item.id)
    }
  },
  { deep: true, immediate: true }
)

const emit = defineEmits(['getCustomerValue', 'closeDrawer', 'refreshPage', 'prev', 'next'])

/*call*/
const onCall = (row, callee) => {
  emitter.emit('simCall', {
    callee,
    source: 'customer',
    sourceId: row.id
  })
  emitter.emit('userCallCallee', callee)
}

/**重新获取线索详情*/
const getCustomer = () => {
  emit('getCustomerValue')
}

/**编辑*/
const formRef = ref()
const openForm = () => {
  formRef.value.open('update', props.CustomerValue.id)
}

/** 客户转移 */
const transferFormRef = ref()
const transfer = () => {
  transferFormRef.value?.open(
    false,
    '客户转移',
    props.CustomerValue.id,
    CustomerApi.transferCustomer
  )
}

const companyDetail = ref(null)
/**企业详情*/
const wentEnt = () => {
  if (props.CustomerValue.entId) {
    companyDetail.value.setDrawer(true, props.CustomerValue.entId, null, null)
  }
}

/**更改成交状态**/
const handleUpdateDealStatus = async () => {
  const dealStatus = !props.CustomerValue.dealStatus
  try {
    await ElMessageBox.confirm(
      `确定更新成交状态为【${dealStatus ? '已成交' : '未成交'}】吗？`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    )
    await CustomerApi.updateCustomerDealStatus(props.CustomerValue.id, dealStatus)
    ElMessage.success('更新成交状态成功')
    getCustomer()
  } catch {}
}

/** 锁定客户 */
const handleLock = async () => {
  try {
    await ElMessageBox.confirm(`确定锁定客户【${props.CustomerValue.name}】吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    await CustomerApi.lockCustomer(unref(props.CustomerValue.id), true)
    ElMessage.success(`锁定客户【${props.CustomerValue.name}】成功`)
    getCustomer()
    emit('refreshPage')
  } catch {}
}

/** 解锁客户 */
const handleUnlock = async () => {
  try {
    await ElMessageBox.confirm(`确定解锁客户【${props.CustomerValue.name}】吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    await CustomerApi.lockCustomer(unref(props.CustomerValue.id), false)
    ElMessage.success(`解锁客户【${props.CustomerValue.name}】成功`)
    getCustomer()
    emit('refreshPage')
  } catch {}
}

/** 客户放入公海 */
const handlePutPool = async () => {
  try {
    await ElMessageBox.confirm(`确定将【${props.CustomerValue.name}】放入公海吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    await CustomerApi.putCustomerPool(unref(props.CustomerValue.id))
    ElMessage.success(`【${props.CustomerValue.name}】放入公海成功`)
    emit('closeDrawer')
    emit('refreshPage')
  } catch {}
}

/**删除线索*/
const delCustomer = async () => {
  try {
    await ElMessageBox.confirm('确定要删除此客户吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    if (props.isPool) {
      await CustomerApi.deleteCustomerPool(props.CustomerValue.id)
    } else {
      await CustomerApi.deleteCustomer(props.CustomerValue.id)
    }
    ElMessage.success('删除成功')
    emit('closeDrawer')
    emit('refreshPage')
  } catch {}
}

const init = () => {
  emit('closeDrawer')
  emit('refreshPage')
}

/**领取线索*/
const handleReceive = async () => {
  try {
    await ElMessageBox.confirm(`确定领取客户【${props.CustomerValue.name}】吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    await CustomerApi.receiveCustomer([unref(props.CustomerValue.id)])
    ElMessage.success(`领取客户【${props.CustomerValue.name}】成功`)
    emit('closeDrawer')
    emit('refreshPage')
  } catch {}
}

/**选择取消标签**/
const changeTag = (id) => {
  const index = tagValue.value.indexOf(id)
  if (index != -1) {
    tagValue.value.splice(index, 1)
  } else {
    tagValue.value.push(id)
  }
}

/**编辑标签*/
const submit = async () => {
  try {
    isLoading.value = true
    let obj = {
      customerId: props.CustomerValue.id,
      labelList: tagValue.value
    }
    await CustomerApi.updateCustomerTag(obj)
    ElMessage.success('操作成功')
    showTagPopup.value = false
    getCustomer()
    emit('refreshPage')
  } finally {
    isLoading.value = false
  }
}

/**单个分配客户*/
const distributeForm = ref()
const handleDistributeForm = async () => {
  distributeForm.value?.open([props.CustomerValue.id], null, props.CustomerValue.moduleId)
}

const getModuleName = (id) => {
  if (props.moduleOption) {
    return props.moduleOption.find((item) => item.id == id)
  }
}
</script>

<style lang="scss" scoped>
.h5-customer-detail {
  background: #f7f8fa;
}

.header-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;

  .customer-info {
    .customer-name-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .customer-name {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
        flex: 1;

        &.ent-customer {
          color: #409eff;
          cursor: pointer;
        }
      }

      .nav-buttons {
        display: flex;
        gap: 8px;
      }
    }

    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .label {
        color: #909399;
        font-size: 14px;
        margin-right: 8px;
        min-width: 60px;
      }

      .value {
        color: #303133;
        font-size: 14px;
      }

      .phone-number {
        color: #409eff;
        font-size: 14px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }

    .tags-section {
      .tags-row {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 4px;

        .edit-tag-btn {
          color: #909399;
          margin-left: 8px;
        }
      }
    }
  }
}

.action-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;

  .action-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 12px 8px;
      background: #f5f7fa;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #ecf5ff;
        color: #409eff;
      }

      .el-icon {
        font-size: 20px;
        margin-bottom: 4px;
      }

      span {
        font-size: 12px;
        text-align: center;
      }
    }
  }
}

.tag-content {
  padding: 16px;

  .tag-group {
    margin-bottom: 16px;

    .group-name {
      font-size: 14px;
      color: #606266;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .tag-list {
      display: flex;
      flex-wrap: wrap;

      .tag-item {
        transition: all 0.3s;

        &:hover {
          transform: scale(1.05);
        }
      }
    }
  }
}
</style>
